<template>
  <a-breadcrumb class="breadcrumb">
    <template v-for="(item, index) in breadcrumbList" :key="index">
      <a-breadcrumb-item>
        <component
          :is="item.click ? 'a' : 'span'"
          v-on="{ click: item.click }"
          >{{ item.name }}</component
        >
      </a-breadcrumb-item>
    </template>
  </a-breadcrumb>
  <div class="content">
    <a-steps :current="currentStep">
      <a-step v-for="item in steps" :key="item.title" :title="item.title" />
    </a-steps>
    <div class="steps-content">
      <a-form
        v-if="currentStep === 0"
        ref="formRef"
        :model="formState"
        name="basic"
        layout="vertical"
      >
        <FormItem
          v-for="item in createBasicInfoForm"
          :key="item.key"
          :formItemConfig="item"
          v-model:formState="formState[item.key || '']"
        ></FormItem>
      </a-form>
      <a-form
        v-else-if="currentStep === 1"
        :model="formState"
        name="basic"
        layout="vertical"
      >
        <FormItem
          v-for="item in createFilterCondtitionForm"
          :key="item.key"
          :formItemConfig="item"
          v-model:formState="formState[item.key || '']"
        ></FormItem>
      </a-form>
      <template v-else>
        <Table :tableProps="tableProps">
          <template #custom="{ record, column, text }">
            <component
              :is="column.dataIndex === `ind3Zh` ? 'a' : 'span'"
              v-bind="
                column.dataIndex === `ind3Zh`
                  ? {
                      href: record.indId
                        ? `/file/indicator/${record.indId}/indicator.html`
                        : undefined,

                      target: '_blank',
                    }
                  : {}
              "
              :class="{ 'wrap-cell': column.dataIndex !== `ind3Zh` }"
              :title="
                column.customRender?.({
                  text,
                  record,
                  column,
                }) || text
              "
              >{{
                column.customRender?.({
                  text,
                  record,
                  column,
                }) ||
                text ||
                "-"
              }}</component
            >
          </template>
        </Table>
        <p v-if="showErrorText" class="error-text">请选择指标</p>
      </template>
    </div>
    <div class="steps-action">
      <a-button
        v-if="currentStep < steps.length - 1"
        type="primary"
        @click="handleNext"
        >{{ currentStep === 1 ? "智能筛选" : "下一步" }}</a-button
      >
      <a-button
        v-if="currentStep == steps.length - 1"
        type="primary"
        @click="handleSubmit"
      >
        一键生成指标体系
      </a-button>
      <a-button
        v-if="currentStep > 0"
        style="margin-left: 8px"
        @click="currentStep--"
        >上一步</a-button
      >
    </div>
  </div>
</template>
<script lang="ts" setup>
import { getCurrentInstance, reactive, ref } from "vue";
import { useRouter } from "vue-router";
import {
  createBasicInfoForm,
  createFilterCondtitionForm,
  getRecommandIndicatorsColumns,
} from "./config";
import FormItem from "@/components/Form/FormItem.vue";
import {
  getRecommendIndicators,
  createIndicatorSystemByIntelligence,
} from "@/api";
import Table from "@/components/Table.vue";
import { PaginationProps } from "ant-design-vue";
import { Key } from "ant-design-vue/es/_util/type";
const { $loading } =
  getCurrentInstance()?.appContext.config.globalProperties || {};
const router = useRouter();
const formRef = ref();
const currentStep = ref(0);
const formState = ref<Record<string, any>>({});
const breadcrumbList = [
  {
    name: "指标体系列表",
    click: () => router.push({ name: "IndicatorSystem" }),
  },
  {
    name: "新建指标体系",
  },
];
const steps = [
  {
    title: "基本信息",
  },
  {
    title: "筛选条件",
  },
  {
    title: "智能推荐",
  },
];
const selectedRowKeys = ref<Key[]>([]);
const onSelectChange = (keys: Key[]) => {
  selectedRowKeys.value = keys;
  if (showErrorText.value) showErrorText.value = false;
};
const showErrorText = ref(false);
const tableProps = reactive<{
  dataSource: Record<string, any>[];
  columns: ColumnItem[];
  pagination: PaginationProps | boolean;
  rowKey: string;
  rowSelection?: any;
}>({
  rowKey: "indId",
  dataSource: [],
  columns: getRecommandIndicatorsColumns(),
  pagination: false,
  rowSelection: {
    fixed: true,
    selectedRowKeys: selectedRowKeys,
    onChange: onSelectChange,
  },
});
const handleFilter = () => {
  $loading?.start();
  return getRecommendIndicators(formState.value)
    .then((res) => {
      tableProps.dataSource = res;
      selectedRowKeys.value = [];
    })
    .finally(() => $loading?.stop());
};
const handleNext = async () => {
  try {
    switch (currentStep.value) {
      case 0:
        await formRef.value?.validate();
        break;
      case 1:
        await handleFilter();
        break;
      default:
        break;
    }
    currentStep.value++;
  } catch (e) {
    console.error(e);
  }
};
const handleSubmit = () => {
  if (!selectedRowKeys.value?.length) {
    showErrorText.value = true;
    return;
  }
  $loading?.start();
  createIndicatorSystemByIntelligence(
    Object.assign(
      {
        indicators: tableProps.dataSource.filter((item) =>
          selectedRowKeys.value.includes(item.indId)
        ),
      },
      formState.value
    )
  )
    .then(() => {
      router.replace("/indicators");
    })
    .catch(console.error)
    .finally(() => $loading?.stop());
};
</script>
<style lang="scss" scoped>
.breadcrumb {
  margin-bottom: 16px;
}
.content {
  background-color: #fff;
  padding: 16px 64px;
}
.steps-content {
  padding-top: 16px;
}
.steps-action {
  margin-top: 16px;
}
.wrap-cell {
  white-space: pre-wrap;
}
.error-text {
  color: #ff4d4f;
  font-size: 14px;
}
</style>
